//
//  GetBackLoginPswVC.swift
//  HengYouCai
//
//  Created by lwj on 2018/3/23.
//  Copyright © 2018年 lwj. All rights reserved.
//

import UIKit
import ReactiveCocoa
import ReactiveSwift

class GetBackLoginPswVC: BaseTableViewController {
    
    ///手机号
    var phoneNumber: String = ""
    
    ///控制是否弹出重新设置登录密码的属性
    var isShowGetBackPswAlertV = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //        self.navigationController.navigationBar.backIndicatorImage = [UIImage imageNamed:@"back"];
        view.backgroundColor = Normal_458Color
//        self.navigationItem.title = "找回登录密码"
        self.wl_navTitle("找回登录密码", titleColor: UIColor.black)

        initUI()
        
        if isShowGetBackPswAlertV == true {
            JCWCommonAlertView(title: "温馨提示", message: "我司为响应国家金融合规进行三级等保评测，现等保要求用户定期修改密码，需要您进行修改密码。", btnTitle: "确定", sureClick: {
            }, isCancle: true)
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back")
        
    }
    func initUI() {
        
        weak var weakSelf = self
        
        self.tableView.separatorColor = UIColor.clear
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: 300))
        headerView.backgroundColor = Normal_458Color
        
        /// 电话号码
        let bgView = UIView()
        bgView.backgroundColor = UIColor.white
        headerView.addSubview(bgView)
        _ = bgView.sd_layout()
            .topSpaceToView(headerView,15)?
            .leftSpaceToView(headerView,0)?
            .rightSpaceToView(headerView,0)?
            .heightIs(45)
        let phoneTitleLab = UILabel()
        phoneTitleLab.text = "手机号码"
        phoneTitleLab.textColor = Normal_333Color
        phoneTitleLab.font = Font_WL(15)
        bgView.addSubview(phoneTitleLab)
        _ = phoneTitleLab.sd_layout()
            .centerYEqualToView(bgView)?
            .leftSpaceToView(bgView,15)?
            .autoHeightRatio(0)?
            .widthIs(90)
        
        let phoneLab = UILabel()
        phoneLab.text = phoneNumber
        phoneLab.textColor = Normal_333Color
        phoneLab.textAlignment = .left
        phoneLab.font = Font_WL(15)
        bgView.addSubview(phoneLab)
        _ = phoneLab.sd_layout()
            .centerYEqualToView(bgView)?
            .leftSpaceToView(phoneTitleLab,0)?
            .rightSpaceToView(bgView,15)?
            .autoHeightRatio(0)
        
        /// 图片验证码
        
        let picVerCode = customCellView("图片验证码", "请输入图片验证码","",true,8,8)
        refreshBtnPicVer(picVerCode.rightBtn)
        picVerCode.rightBtn.imageEdgeInsets = UIEdgeInsets(top: -10, left: 0, bottom: 10, right: 0)
        headerView.addSubview(picVerCode)
        
        _ = picVerCode.sd_layout()
            .topSpaceToView(bgView,0.5)?
            .leftSpaceToView(headerView,0)?
            .rightSpaceToView(headerView,0)?
            .heightIs(45)
        
        /// 点击验证码 重新获取
        picVerCode.rightBtn.addTarget(self, action: #selector(refreshBtnPicVer(_:)), for: .touchUpInside)
        
        /// 手机验证码
        let phoneVerCode = customCellView("手机验证码", "请输入手机验证码","获取验证码",false,0,0)
        headerView.addSubview(phoneVerCode)
        
        _ = phoneVerCode.sd_layout()
            .topSpaceToView(picVerCode,0.5)?
            .leftSpaceToView(headerView,0)?
            .rightSpaceToView(headerView,0)?
            .heightIs(45)
        phoneVerCode.rightBtn.reactive.controlEvents(.touchUpInside).observeValues { (btn) in
            if (picVerCode.inputFieldView.text?.count)! < 3 {
                weakSelf?.view.showHUDWarnTips("图片验证码不正确", hideDelay: kHUDHideDelay)
                return
            }else{
                btn.isEnabled = false
                weakSelf?.getPhoneCode(btn,picVerCode.rightBtn,picVerCode.inputFieldView.text!)
            }
        }
        
        /// 登录密码
        let loginPswView = customCellView("登录密码", "设置新的登录密码","uneye",true,0,0)
        headerView.addSubview(loginPswView)
        
        _ = loginPswView.sd_layout()
            .topSpaceToView(phoneVerCode,15)?
            .leftSpaceToView(headerView,0)?
            .rightSpaceToView(headerView,0)?
            .heightIs(45)
        loginPswView.inputFieldView.isSecureTextEntry = true
        loginPswView.rightBtn.reactive.controlEvents(.touchUpInside).observeValues { (btn) in
            loginPswView.inputFieldView.isSecureTextEntry = btn.isSelected
            
            btn.isSelected = !btn.isSelected
            
            if btn.isSelected{
                btn.setImage(UIImage(named: "eye"), for: .normal)
            }else{
                btn.setImage(UIImage(named: "uneye"), for: .normal)
                
            }
        }
        /// 温馨提示
        let noticeLab = UILabel()
        noticeLab.textColor = Normal_999Color
        noticeLab.text = "密码区分大小写，建议使用8位以上字母/数字组合"
        noticeLab.textAlignment = .left
        noticeLab.font = Font_WL(12)
        noticeLab.backgroundColor = UIColor.clear
        headerView.addSubview(noticeLab)
        
        _ = noticeLab.sd_layout()
            .topSpaceToView(loginPswView,7.5)?
            .leftSpaceToView(headerView,15)?
            .rightSpaceToView(headerView,15)?
            .autoHeightRatio(0)
        
        let certainBtn = UIButton(type: .custom)
        certainBtn.setTitle("确认", for: .normal)
        certainBtn.setTitleColor(UIColor.white, for: .normal)
        certainBtn.backgroundColor = Normal_BBBColor
        certainBtn.layer.cornerRadius = 5
        certainBtn.isEnabled = false
        certainBtn.titleLabel?.font = Font_WL(15)
        headerView.addSubview(certainBtn)
        
        _ = certainBtn.sd_layout()
            .topSpaceToView(noticeLab,30)?
            .leftSpaceToView(headerView,15)?
            .rightSpaceToView(headerView,15)?
            .heightIs(45)
        certainBtn.reactive.controlEvents(.touchUpInside).observeValues { (btn) in
            weakSelf?.sure(phoneVerCode.inputFieldView.text!, loginPswView.inputFieldView.text!)
        }
        
        changePswCombineSingle(phoneCode: phoneVerCode.inputFieldView, pswCode: loginPswView.inputFieldView, picCode: picVerCode.inputFieldView, btn: certainBtn)
        
        self.tableView.tableHeaderView = headerView
    }
    
    /// 获取短信验证码
    func getPhoneCode( _ phoneBtn : UIButton, _ picVerBtn : UIButton, _ captcha: String) {
        
        weak var weakSelf = self
        HYCNetService.getReSetPwdCode(withDict: ["mobile":self.phoneNumber,"captcha":captcha], onSuccess: { (result) in
            //
            let resultDic : Dictionary = result!
            
            weakSelf?.view.showHUDWarnTips(resultDic["message"] as? String ?? "" , hideDelay: kHUDHideDelay)
            
            customTimer(phoneBtn)
            weakSelf?.refreshBtnPicVer(picVerBtn)
        }, andFailed: { (code, errMsg) in
            //
            weakSelf?.view.showHUDWarnTips(errMsg, hideDelay: kHUDHideDelay)
            phoneBtn.isEnabled = true
            
        })
        
        
    }
    /// 刷新图片验证码
    func refreshBtnPicVer(_ currBtn : UIButton)  {
        do {
            let imgData = try Data(contentsOf: URL(string: JCW_GenerateImage)!)
            //                img = UIImage(data: imgData)!
            currBtn.setBackgroundImage(UIImage(data: imgData), for: .normal)
            
        }catch{}
    }
    func sure(_ mobileCode: String, _ password : String ) {
        
        weak var weakSelf = self
        self.view.endEditing(true)
        self.view.showHUDLoading()
        HYCNetService.reSetPwd(withDict: ["mobileCode":mobileCode,"mobile":self.phoneNumber,"password":password], onSuccess: { (result) in
            //
            let resultDic : Dictionary = result!
            
            let sucMsg : String = resultDic["message"] as! String
            
            weakSelf?.view.showHUDSuccessTips(sucMsg, hideDelay: kHUDHideDelay)
            weakSelf?.perform(#selector(weakSelf?.currentPopVC), with: nil, afterDelay: kHUDHideDelay)
        }) { (code, errMsg) in
            //
            weakSelf?.view.showHUDFailTips(errMsg, hideDelay: kHUDHideDelayB)
        }
        
    }
    func currentPopVC() {
        self.navigationController?.popViewController(animated: true)

    }
    /// 确认聚合信号 监听按钮的颜色与enable
    func changePswCombineSingle(phoneCode : UITextField, pswCode : UITextField, picCode:UITextField, btn : UIButton) {
        //
        
        let picSingle = picCode.reactive.continuousTextValues.map { (text) -> Bool in
            
            return text!.count > 0
        }
        let pswSingle = pswCode.reactive.continuousTextValues.map { (text) -> Bool in
            
            return text!.count > 0
        }
        
        let phoneSingle = phoneCode.reactive.continuousTextValues.map { (text) -> Bool in
            
            return text!.count > 0
        }
        
        let btnSingle = Signal.combineLatest(picSingle,pswSingle,phoneSingle).map { (pic,psw,phone) in
            //
            return pic && psw && phone
        }
        btnSingle.map { nextBtnSingle in
            let enable =  (nextBtnSingle)
            btn.isEnabled = enable
            return enable ? Normal_RedColor : Normal_BBBColor
            }.observeValues { (nextBtnColor) in
                btn.backgroundColor = nextBtnColor
        }
        
        
        
    }
}

/// 倒计时
func customTimer(_ btn : UIButton) {
    
    btn.setTitleColor(Normal_999Color, for: .normal)
    // 定义需要计时的时间
    var timeCount = 60
    // 在global线程里创建一个时间源
    let codeTimer = DispatchSource.makeTimerSource(queue:      DispatchQueue.global())
    // 设定这个时间源是每秒循环一次，立即开始
    codeTimer.scheduleRepeating(deadline: .now(), interval: .seconds(1))
    // 设定时间源的触发事件
    codeTimer.setEventHandler(handler: {
        // 每秒计时一次
        print(timeCount)
        // 时间到了取消时间源
        if timeCount <= 0 {
            DispatchQueue.main.async {
                btn.isEnabled = true
                btn.setTitle("再次获取", for: .normal)
                btn.setTitleColor(Normal_RedColor, for: .normal)
            }
            codeTimer.cancel()
            
        }else{
            // 返回主线程处理一些事件，更新UI等等
            DispatchQueue.main.async {
                btn.setTitle(String(format: "%d秒后重试",timeCount), for: .normal)
            }
        }
        timeCount = timeCount - 1
        
        
    })
    // 启动时间源
    codeTimer.resume()
}
/// 自定义view 模仿cell
class customCellView: UIView {
    
    convenience init(_ titleStr: String?, _ placeHolder: String?, _ btnContent:String?, _ isImg:Bool,_ btnTop:CGFloat, _ btnBottom:CGFloat) {
        self.init(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: 45))
        
        self.backgroundColor = UIColor.white
        
        let title = UILabel()
        title.text = titleStr
        title.textColor = Normal_333Color
        title.textAlignment = .left
        title.font = Font_WL(15)
        self.addSubview(title)
        
        _ = title.sd_layout()
            .leftSpaceToView(self,15)?
            .topSpaceToView(self,0)?
            .bottomSpaceToView(self,0)?
            .widthIs(90)
        
        self.addSubview(inputFieldView)
        inputFieldView.placeholder = placeHolder
        _ = inputFieldView.sd_layout()
            .leftSpaceToView(title,0)?
            .topSpaceToView(self,0)?
            .bottomSpaceToView(self,0)?
            .rightSpaceToView(self,80)
        
        self.addSubview(rightBtn)
        if isImg {
            rightBtn.setImage(UIImage(named: btnContent!), for: .normal)
        }else{
            rightBtn.setTitle(btnContent, for: .normal)
        }
        _ = rightBtn.sd_layout()
            .rightSpaceToView(self,8)?
            .topSpaceToView(self,btnTop)?
            .bottomSpaceToView(self,btnBottom)?
            .widthIs(80)
    }
    
    lazy var inputFieldView: UITextField = {
        let temp = UITextField()
        
        temp.textAlignment = .left
        temp.textColor = Normal_666Color
        temp.font = Font_WL(15)
        return temp
    }()
    
    lazy var rightBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setTitleColor(Normal_RedColor, for: .normal)
        temp.titleLabel?.textAlignment = .right
        temp.titleLabel?.font = Font_WL(15)
        //        temp.c
        temp.imageEdgeInsets = UIEdgeInsets(top: 0, left: 25, bottom: 0, right: -25)
        return temp
    }()
}

